package com.sxu.demo.reentrantlock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

import static java.lang.Thread.sleep;

// 锁超时
public class Test3 {
    private static ReentrantLock reentrantLock = new ReentrantLock();
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(()->{
            // 尝试获得锁
            System.out.println(Thread.currentThread().getName()+"：尝试获得锁");
            try {
                // 带超时时间的 指定时间内未获得锁，就会返回false
                if (!reentrantLock.tryLock(3, TimeUnit.SECONDS)){
    //            if (!reentrantLock.tryLock()){
                    System.out.println(Thread.currentThread().getName()+"：获得不到锁");
                    return;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
                System.out.println(Thread.currentThread().getName()+"：获得不到锁");
                return;
            }
            try {
                System.out.println(Thread.currentThread().getName()+"：获得到锁");
            } finally {
                reentrantLock.unlock();
            }
        },"t1");
        reentrantLock.lock();
        System.out.println(Thread.currentThread().getName()+"：获得到锁");
        t1.start();
        sleep(1000);
        System.out.println(Thread.currentThread().getName()+"：释放锁");
        reentrantLock.unlock();
    }
}
